package com.augurit.agmobile.agwater5.drainage.common.tabview;

import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;

import com.example.arm.ext.ScreenUtilKt;
import com.example.drainage.R;
import com.google.android.material.tabs.TabLayout;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @PROJECT MyApplication
 * @USER Augurit
 * @CREATE 2020/11/18 14:28
 */
public class TabLayoutHelper {
    public static void addTabs(TabLayout tabLayout, String... texts) {
        for (int i = 0; i < texts.length; i++) {
            addTab(tabLayout, texts[i], i == 0, i == texts.length - 1);
        }
    }
    public static void addTabs(TabLayout tabLayout, List<String> texts) {
        for (int i = 0; i < texts.size(); i++) {
            addTab(tabLayout, texts.get(i), i == 0, i == texts.size() - 1);
        }
    }

    public static void addTabs(TabLayout tabLayout, int leftResId, int middleResId, int rightResId, String... texts) {
        for (int i = 0; i < texts.length; i++) {
            addTab(tabLayout, texts[i], i == 0, i == texts.length - 1, leftResId, middleResId, rightResId);
        }
    }

    public static void addTabs(TabLayout tabLayout, int leftResId, int middleResId, int rightResId, List<String> texts) {
        for (int i = 0; i < texts.size(); i++) {
            addTab(tabLayout, texts.get(i), i == 0, i == texts.size() - 1, leftResId, middleResId, rightResId);
        }
    }

    public static void addMiddleDivider(TabLayout tabLayout, int resDivider) {
        addDivider(tabLayout, ContextCompat.getDrawable(tabLayout.getContext(), resDivider), 0, LinearLayout.SHOW_DIVIDER_MIDDLE);
    }

    public static void addMiddleDivider(TabLayout tabLayout, int color, int width, int height) {
        final GradientDrawable drawable = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, new int[]{color, color});
        drawable.setSize(ScreenUtilKt.getDpInt(width), ScreenUtilKt.getDpInt(height));
        addMiddleDivider(tabLayout, drawable);
    }

    public static void addMiddleDivider(TabLayout tabLayout, Drawable drawable) {
        addDivider(tabLayout, drawable, 0, LinearLayout.SHOW_DIVIDER_MIDDLE);
    }

    public static void addDivider(TabLayout tabLayout, int color) {
        final ViewGroup.LayoutParams layoutParams = tabLayout.getLayoutParams();
        addDivider(tabLayout, color, ScreenUtilKt.getDpInt(1), layoutParams.height);
    }

    public static void addDivider(TabLayout tabLayout, int color, int width, int height) {
        final GradientDrawable dividerDrawable = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, new int[]{color, color});
        dividerDrawable.setSize(width, height);
        addDivider(tabLayout, dividerDrawable, 0, LinearLayout.SHOW_DIVIDER_MIDDLE);
    }

    public static void addDivider(TabLayout tabLayout, Drawable divider, int padding, int showDividers) {
        View child = tabLayout.getChildAt(0);
        if (child instanceof LinearLayout) {
            final LinearLayout llRoot = (LinearLayout) child;
            llRoot.setDividerDrawable(divider);
            llRoot.setDividerPadding(padding);
            llRoot.setShowDividers(showDividers);
        }
    }

    public static void appendTabs(TabLayout tabLayout, int leftResId, int middleResId, int rightResId, String... texts) {
        final int tabCount = tabLayout.getTabCount();
        if (tabCount <= 0) {
            addTabs(tabLayout, leftResId, middleResId, rightResId, texts);
        } else {
            TabLayout.Tab lastTab = tabLayout.getTabAt(tabCount - 1);
            tabLayout.removeTabAt(tabCount - 1);
            assert lastTab != null;
            assert lastTab.getText() != null;
            addTab(tabLayout, lastTab.getText().toString(), tabLayout.getTabCount() == 0, false, leftResId, middleResId, rightResId);
            for (int i = 0; i < texts.length; i++) {
                addTab(tabLayout, texts[i], false, i == texts.length - 1, leftResId, middleResId, rightResId);
            }
        }
    }

    public static void appendTab(TabLayout tabLayout, int leftResId, int middleResId, int rightResId, String text) {
        final int tabCount = tabLayout.getTabCount();
        if (tabCount <= 0) {
            addTab(tabLayout, text, true, false, leftResId, middleResId, rightResId);
        } else {
            TabLayout.Tab lastTab = tabLayout.getTabAt(tabCount - 1);
            assert lastTab != null;
            assert lastTab.getText() != null;
            final String lastTabText = lastTab.getText().toString();
            tabLayout.removeTabAt(tabCount - 1);
            addTab(tabLayout, lastTabText, tabLayout.getTabCount() == 0, false, leftResId, middleResId, rightResId);
            addTab(tabLayout, text, false, true, leftResId, middleResId, rightResId);
        }
    }

    public static void setOnTabSelectedChangeListener(TabLayout tabLayout, OnTabSelectedChangeListener listener) {
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (listener != null) {
//                    final String text;
//                    if (tab.getText() != null) text = tab.getText().toString();
//                    else text = "";
                    final String text = tab.getText() != null ? tab.getText().toString() : "";
                    listener.onTabSelectedChange(tab.getPosition(), text, true);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (listener != null) {
//                    final String text;
//                    if (tab.getText() != null) text = tab.getText().toString();
//                    else text = "";
                    final String text = tab.getText() != null ? tab.getText().toString() : "";
                    listener.onTabSelectedChange(tab.getPosition(), text, false);
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    private static void addTab(TabLayout tabLayout, String text, boolean isStart, boolean isEnd) {
        addTab(tabLayout, text, isStart, isEnd, R.drawable.selector_tab_left_bg, R.drawable.selector_tab_middle_bg, R.drawable.selector_tab_right_bg);
    }

    private static void addTab(TabLayout tabLayout, String text, boolean isStart, boolean isEnd, int leftResId, int middleResId, int rightResId) {
        if (isStart) {
            addTab(tabLayout, text, leftResId);
        } else if (isEnd) {
            addTab(tabLayout, text, rightResId);
        } else {
            addTab(tabLayout, text, middleResId);
        }
    }

    private static void addTab(TabLayout tabLayout, String text, int resId) {
        TabLayout.Tab tab = tabLayout.newTab();
        tab.setText(text);
        if (resId != -1) {
            final Drawable drawable = ResourcesCompat.getDrawable(tabLayout.getResources(), resId, null);
            try {
                Class<TabLayout.Tab> tabClass = TabLayout.Tab.class;
                // support 27.1.1
                Field viewField = tabClass.getDeclaredField("mView");
                // support 28.0.0
//            Field viewField = tabClass.getDeclaredField("view");
                viewField.setAccessible(true);
                Object viewObj = viewField.get(tab);
                Method setBackground = View.class.getMethod("setBackground", Drawable.class);
                setBackground.setAccessible(true);
                setBackground.invoke(viewObj, drawable);
//            Method setBackground = View.class.getMethod("setBackground", Drawable.class);
//            setBackground.setAccessible(true);
//            setBackground.invoke(tab.view, drawable);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        tabLayout.addTab(tab);
    }

    public static void updateText(TabLayout tabLayout, String... txts) {
        if (txts.length != 0) {
            for (int i = 0; i < txts.length; i++) {
                tabLayout.getTabAt(i).setText(txts[i]);
            }
        }
    }

    public static TextView getTextView(TabLayout.Tab tab) {
        if (tab != null) {
            try {
                Class<TabLayout.Tab> tabClz = TabLayout.Tab.class;
                Field mViewField = tabClz.getDeclaredField("mView");
                mViewField.setAccessible(true);
                Object mView = mViewField.get(tab);
                if (mView != null) {
                    Class<?> tabViewClz = Class.forName("android.support.design.widget.TabLayout$TabView");
                    if (tabViewClz != null) {
                        Field mTextViewField = tabViewClz.getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);
                        Object mTextView = mTextViewField.get(mView);
                        if (mTextView instanceof TextView) {
                            return (TextView) mTextView;
                        }
                    }
                }
            } catch (NoSuchFieldException | IllegalAccessException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void setTextSize(TabLayout tabLayout, float textSize) {
        int tabCount = tabLayout.getTabCount();
        for (int i = 0; i < tabCount; i++) {
            setTextSize(tabLayout.getTabAt(i), textSize);
        }
    }

    public static void setTextSize(TabLayout.Tab tab, float textSize) {
        final TextView textView = getTextView(tab);
        if (textView != null) {
            textView.setTextSize(textSize);
        }
    }

    public static void setTextBold(TabLayout.Tab tab, boolean bold) {
        TextView textView = getTextView(tab);
        if (textView != null) {
            textView.getPaint().setFakeBoldText(bold);
            textView.postInvalidate();
        }
    }

    public interface OnTabSelectedChangeListener {
        void onTabSelectedChange(int position, String text, boolean isSelected);
    }
}
